import React, { useState, useCallback } from 'react'
import ReactDOM from 'react-dom'
import { CSSTransition } from 'react-transition-group'

const Modal = ({ isShowing, close, container, children }) =>
  ReactDOM.createPortal(
    <CSSTransition in={isShowing} timeout={200} unmountOnExit={true}>
      {(value) => children}
    </CSSTransition>,
    container,
  )

const useModal = (init = false) => {
  const [isShowing, setIsShowing] = useState(init)

  const handleToggle = useCallback(
    (state) => {
      if (state === undefined || typeof state !== 'boolean') {
        setIsShowing(!isShowing)
      } else {
        setIsShowing(state)
      }
    },
    [isShowing],
  )

  return {
    modalDom: (children = '') =>
      Modal({
        isShowing: isShowing,
        close: () => handleToggle(false),
        container: document.body,
        children: children,
      }),
    toggleModal: handleToggle,
    showState: isShowing,
  }
}

export default useModal
